<template>
  <div class="news-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>电影资讯</h2>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索资讯..."
          clearable
          @keyup.enter="handleSearch"
          @clear="handleClearSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 分类筛选 -->
    <div class="category-filter">
      <el-radio-group v-model="currentCategory" @change="handleCategoryChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button 
          v-for="category in newsCategories" 
          :key="category.id" 
          :label="category.id"
        >
          {{ category.name }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 置顶资讯 -->
    <div v-if="topNews.length > 0" class="top-news-section">
      <h3 class="section-title">置顶资讯</h3>
      <div class="top-news-list">
        <div 
          v-for="news in topNews" 
          :key="news.id" 
          class="top-news-item"
          @click="goToDetail(news.id)"
        >
          <div class="top-news-cover">
            <img 
              :src="getImageUrl(news.coverImage)" 
              :alt="news.title" 
              @error="handleImageError"
            />
            <div class="top-badge">置顶</div>
          </div>
          <div class="top-news-content">
            <h4 class="top-news-title">{{ news.title }}</h4>
            <p class="top-news-summary">{{ getSummary(news.content) }}</p>
            <div class="top-news-meta">
              <span class="category-tag">{{ getCategoryName(news.categoryId) }}</span>
              <span class="view-count">👁 {{ news.viewCount }}</span>
              <span class="publish-time">{{ formatTime(news.publishTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 资讯列表 -->
    <div class="news-list-section">
      <div class="section-header">
        <h3 class="section-title">资讯列表</h3>
        <div class="sort-options">
          <el-radio-group v-model="currentSort" @change="handleSortChange" size="small">
            <el-radio-button label="time">最新</el-radio-button>
            <el-radio-button label="view">热门</el-radio-button>
            <el-radio-button label="like">点赞</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <div v-else-if="newsList.length === 0" class="empty-state">
        <div class="empty-icon">📰</div>
        <h4>暂无资讯</h4>
        <p>当前分类下暂无资讯内容</p>
      </div>

      <div v-else class="news-list">
        <div 
          v-for="news in newsList" 
          :key="news.id" 
          class="news-item"
          @click="goToDetail(news.id)"
        >
          <div class="news-cover">
            <img 
              :src="getImageUrl(news.coverImage)" 
              :alt="news.title" 
              @error="handleImageError"
            />
          </div>
          <div class="news-content">
            <h4 class="news-title">{{ news.title }}</h4>
            <p class="news-summary">{{ getSummary(news.content) }}</p>
            <div class="news-meta">
              <span class="category-tag">{{ getCategoryName(news.categoryId) }}</span>
              <div class="meta-right">
                <span class="view-count">👁 {{ news.viewCount }}</span>
                <span class="like-count">❤️ {{ news.likeCount }}</span>
                <span class="publish-time">{{ formatTime(news.publishTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > pageSize" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { newsAPI } from '../services/apiService'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const currentCategory = ref('')
const currentSort = ref('time')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const topNews = ref([])
const newsList = ref([])
const newsCategories = ref([])

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  if (newVal === '') {
    loadNewsList()
  }
})

// 生命周期
onMounted(() => {
  loadNewsCategories()
  loadTopNews()
  loadNewsList()
})

// 加载资讯分类
const loadNewsCategories = async () => {
  try {
    const response = await newsAPI.getActiveCategoriesByType('news')
    if (response.success) {
      newsCategories.value = response.data || []
    }
  } catch (error) {
    console.error('加载资讯分类失败:', error)
  }
}

// 加载置顶资讯
const loadTopNews = async () => {
  try {
    const response = await newsAPI.getTopNews()
    if (response.success) {
      topNews.value = response.data || []
    }
  } catch (error) {
    console.error('加载置顶资讯失败:', error)
  }
}

// 加载资讯列表
const loadNewsList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      sort: currentSort.value,
      isPublished: true
    }
    
    if (currentCategory.value) {
      params.categoryId = currentCategory.value
    }

    let response
    if (searchKeyword.value) {
      response = await newsAPI.searchNews(searchKeyword.value, params)
    } else {
      response = await newsAPI.getNewsList(params)
    }

    if (response.success) {
      newsList.value = response.data?.content || []
      total.value = response.data?.totalElements || 0
    }
  } catch (error) {
    console.error('加载资讯列表失败:', error)
    ElMessage.error('加载资讯列表失败')
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  loadNewsList()
}

const handleClearSearch = () => {
  searchKeyword.value = ''
  loadNewsList()
}

const handleCategoryChange = () => {
  currentPage.value = 1
  loadNewsList()
}

const handleSortChange = () => {
  currentPage.value = 1
  loadNewsList()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadNewsList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadNewsList()
}

const goToDetail = (id) => {
  router.push(`/news/${id}`)
}

// 图片处理函数
const getImageUrl = (imageUrl) => {
  // 如果图片URL为空或无效，直接返回默认图片
  if (!imageUrl || imageUrl.trim() === '') {
    return '/images/news-default.jpeg'
  }
  
  // 如果是相对路径，确保以/开头
  if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
    return '/' + imageUrl
  }
  
  return imageUrl
}

// 图片加载错误处理
const handleImageError = (event) => {
  const img = event.target
  // 如果当前不是默认图片，则替换为默认图片
  if (img.src !== '/images/news-default.jpeg') {
    img.src = '/images/news-default.jpeg'
    // 防止无限循环错误
    img.onerror = null
  }
}

// 工具函数
const getSummary = (content) => {
  if (!content) return ''
  // 移除HTML标签
  const text = content.replace(/<[^>]*>/g, '')
  return text.length > 100 ? text.substring(0, 100) + '...' : text
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60 * 1000) {
    return '刚刚'
  } else if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前'
  } else if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
  } else {
    return date.toLocaleDateString()
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '未知分类'
  const category = newsCategories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未知分类'
}
</script>

<style scoped>
.news-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0;
  color: var(--text);
}

.search-box {
  width: 300px;
}

.category-filter {
  margin-bottom: 30px;
  text-align: center;
}

.top-news-section {
  margin-bottom: 40px;
}

.section-title {
  margin-bottom: 20px;
  color: var(--text);
  font-size: 1.5rem;
}

.top-news-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.top-news-item {
  display: flex;
  background: var(--card);
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.top-news-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.top-news-cover {
  position: relative;
  width: 300px;
  flex-shrink: 0;
}

.top-news-cover img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.top-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background: #e53e3e;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.top-news-content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.top-news-title {
  margin: 0 0 10px 0;
  font-size: 1.3rem;
  color: var(--text);
  line-height: 1.4;
}

.top-news-summary {
  color: var(--muted);
  line-height: 1.6;
  margin-bottom: 15px;
}

.top-news-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 0.9rem;
  color: var(--muted);
  flex-wrap: wrap;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.news-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.news-item {
  display: flex;
  background: var(--card);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.news-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.news-cover {
  width: 200px;
  flex-shrink: 0;
}

.news-cover img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.news-content {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.news-title {
  margin: 0 0 10px 0;
  font-size: 1.1rem;
  color: var(--text);
  line-height: 1.4;
}

.news-summary {
  color: var(--muted);
  line-height: 1.6;
  margin-bottom: 10px;
  flex: 1;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.85rem;
  color: var(--muted);
  flex-wrap: wrap;
  gap: 15px;
  min-height: 24px;
}

.category-tag {
  background: var(--primary);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.meta-right {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--muted);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .top-news-item {
    flex-direction: column;
  }
  
  .top-news-cover {
    width: 100%;
  }
  
  .news-item {
    flex-direction: column;
  }
  
  .news-cover {
    width: 100%;
  }
  
  .news-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    min-height: auto;
  }
  
  .meta-right {
    width: 100%;
    justify-content: space-between;
    gap: 10px;
  }
}
</style>